<template>
  <div>
    <input
      type="file"
      ref="myInput"
      id="uploads"
      style="position:absolute; clip:rect(0 0 0 0);"
      accept="image/png, image/jpeg, image/gif, image/jpg"
      @change="uploadImg($event, 1)"
    />
    <el-dialog
      :append-to-body="appendToBody"
      :title="ImgUtilsTitle"
      :visible.sync="addImg"
      @close="handleDialogClose"
      :close-on-click-modal="false"
    >
      <div style="width: 100%;height: 550px;" v-show="!progressShow">
        <vue-cropper
          ref="cropper"
          :img="cropperOptionData.img"
          :output-size="cropperOptionData.size"
          :output-type="cropperOptionData.outputType"
          :info="true"
          :full="cropperOptionData.full"
          :can-move="cropperOptionData.canMove"
          :can-move-box="cropperOptionData.canMoveBox"
          :fixed-box="cropperOptionData.fixedBox"
          :original="cropperOptionData.original"
          :auto-crop="cropperOptionData.autoCrop"
          :auto-crop-width="cropperOptionData.autoCropWidth"
          :auto-crop-height="cropperOptionData.autoCropHeight"
          :center-box="cropperOptionData.centerBox"
          @real-time="realTime"
          :high="cropperOptionData.high"
          @img-load="imgLoad"
          mode="cover"
        ></vue-cropper>
      </div>
      <div
        style="width: 100%;position: relative;display: flex;align-items: center;justify-content: center;height: 300px;background: rgba(0,0,0,0.1);margin-bottom: 15px;"
        v-show="progressShow"
      >
        <el-progress type="circle" :percentage="progress"></el-progress>
      </div>
      <div slot="footer" class="dialog-footer" v-show="!progressShow">
        <el-button @click="gloablImgCancel">取 消</el-button>
        <el-button type="primary" @click="gloablImgConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
module.exports = {
  data() {
    return {
      progress: 0,
      progressShow: false,
      ImgUtilsTitle: "",
      addImg: false,
      time: null,
      closeDialogTime: null
    };
  },
  props: {
    cropperOptionData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    isImgUpdata: {
      type: Boolean,
      default: false
    },
    appendToBody: {
      type: Boolean,
      defaule: false
    }
  },
  destroyed(){
    clearTimeout(this.time);
    this.time = null
  },
  methods: {
    uploadImg(e, num) {
      //上传图片
      // this.option.img
      var file = e.target.files[0];
      if (!/\.(gif|jpg|jpeg|png|bmp|GIF|JPG|PNG)$/.test(e.target.value)) {
        alert("图片类型必须是.gif,jpeg,jpg,png,bmp中的一种");
        return false;
      }
      var reader = new FileReader();
      reader.onload = e => {
        let data;
        if (typeof e.target.result === "object") {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        if (num === 1) {
          this.cropperOptionData.img = data;
        } else if (num === 2) {
          this.example2.img = data;
        }
      };
      // 转化为base64
      // reader.readAsDataURL(file)
      // 转化为blob
      reader.readAsArrayBuffer(file);
      this.addImg = true;
      this.ImgUtilsTitle = "添加图片";
    },
    realTime() {},
    imgLoad() {},
    gloablImgCancel() {
      this.addImg = false;
    },
    gloablImgConfirm() {
      this.progressShow = true;
      this.$refs.cropper.getCropBlob(data => {
        // console.log(data, 'data cropper')
        var img = window.URL.createObjectURL(data);
        const isImgUpdata = this.isImgUpdata;
        // this.$emit("img-url-transmit", img, isImgUpdata);
        http(config.url + "admin/cosv5", "POST", {})
          .then(pos => {
            Bucket = pos.data.Bucket;
            Region = pos.data.Region;
            const CDN = pos.data.CDN;
            console.log(pos, "http pos");
            this.uploadImgFn(data, Bucket, Region)
              .then(imgUpload => {
                const imgUrl = CDN + "/" + imgUpload.Key;
                console.log(imgUpload, imgUrl, "imgUpload");
                this.addImg = false;
                this.$emit("img-url-transmit", imgUrl, isImgUpdata);
                this.cropperOptionData.img = "";
              })
              .catch(imgUploaderr => {
                this.$message({
                  showClose: true,
                  message: "上传失败",
                  type: "error"
                });
                console.log(imgUploaderr);
              });
          })
          .catch(err => {
            // console.log(err, "err");
            this.$message({
              showClose: true,
              message: "链接服务器失败",
              type: "error"
            });
          });
        // this.addImg = false;
      });
    },
    handleDialogClose() {
      this.progressShow = false
    },
    uploadImgFn(imgUrl, Bucket, Region) {
      const that = this;
      return new Promise((res, rej) => {
        cos.sliceUploadFile(
          {
            Bucket,
            Region,
            Key: "images/" + new Date().getTime(),
            Body: imgUrl,
            onHashProgress: function(progressData) {
              console.log("校验中", JSON.stringify(progressData));
            },
            onProgress: function(progressData) {
              // , JSON.stringify(progressData)
              console.log("上传中", progressData.percent, progressData.speed);
              const progress =
                Math.round((progressData.loaded / progressData.total) * 10000) /
                100;
              that.progress = progress;
              // var time;
              clearTimeout(that.time);
              that.time = setTimeout(() => {
                that.progressShow = false;
                that.progress = 0;
              }, 200);
              console.log(progress, "progress");
            }
          },
          (err, data) => {
            if (err) {
              rej(err);
            } else {
              res(data);
            }
          }
        );
      });
    }
  }
};
</script>
<style scoped>
</style>